package com.junzhiit.nengji.cms.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.bainaeco.framework.util.DateUtil;
import com.bainaeco.framework.util.EncryptMD5Util;
import com.junzhiit.nengji.bo.GoodsBO;
import com.junzhiit.nengji.bo.GoodsListBO;
import com.junzhiit.nengji.bo.SendPhoneMessageBO;
import com.junzhiit.nengji.bo.ShopBO;
import com.junzhiit.nengji.bo.ShopInfoBO;
import com.junzhiit.nengji.bo.WechatConfigBO;
import com.junzhiit.nengji.cms.rabbitmq.RabbitMQService;
import com.junzhiit.nengji.cms.service.ShopService;
import com.junzhiit.nengji.cms.web.exception.ChainNotFoundException;
import com.junzhiit.nengji.cms.web.exception.EmailIsExistException;
import com.junzhiit.nengji.cms.web.exception.InconsistentPasswordException;
import com.junzhiit.nengji.cms.web.exception.LimitControlException;
import com.junzhiit.nengji.cms.web.exception.MobilePhoneCodeErrorException;
import com.junzhiit.nengji.cms.web.exception.MobilePhoneCodeTimeoutException;
import com.junzhiit.nengji.cms.web.exception.MobilePhoneHasUsedException;
import com.junzhiit.nengji.cms.web.exception.RegisteredFailureException;
import com.junzhiit.nengji.cms.web.exception.RoleNotFoundException;
import com.junzhiit.nengji.cms.web.exception.SendSMSFaileException;
import com.junzhiit.nengji.cms.web.exception.ShopNotFoundException;
import com.junzhiit.nengji.cms.web.exception.WechatConfigNotFoundException;
import com.junzhiit.nengji.cms.web.util.CMSCodeStatus;
import com.junzhiit.nengji.cms.web.util.Constants;
import com.junzhiit.nengji.cms.web.util.ViewObjectUtil;
import com.junzhiit.nengji.cms.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.cms.web.util.aliyun.SmsUtil;
import com.junzhiit.nengji.cms.web.util.aliyun.bean.SMSParams;
import com.junzhiit.nengji.cms.web.util.wechat.WeChatUtils;
import com.junzhiit.nengji.cms.web.vo.DataTablesParamVO;
import com.junzhiit.nengji.cms.web.vo.GoodsListVO;
import com.junzhiit.nengji.cms.web.vo.PhoneCodeVO;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.cms.web.vo.ShopAddVO;
import com.junzhiit.nengji.cms.web.vo.ShopEditVO;
import com.junzhiit.nengji.cms.web.vo.ShopSelectVO;
import com.junzhiit.nengji.cms.web.vo.ShopUpdateVO;
import com.junzhiit.nengji.cms.web.vo.ShopVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserAddVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.cms.web.vo.WechatConfigVO;
import com.junzhiit.nengji.dao.ChainDAO;
import com.junzhiit.nengji.dao.GoodsDAO;
import com.junzhiit.nengji.dao.RoleDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.ShopInfoDAO;
import com.junzhiit.nengji.dao.ShopsLocatedDAO;
import com.junzhiit.nengji.dao.SystemUserDAO;
import com.junzhiit.nengji.dao.SystemUserRoleDAO;
import com.junzhiit.nengji.dao.WechatConfigDAO;
import com.junzhiit.nengji.dao.cache.BankCardCheckCountDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Chain;
import com.junzhiit.nengji.model.Goods;
import com.junzhiit.nengji.model.Role;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.ShopInfo;
import com.junzhiit.nengji.model.ShopsLocated;
import com.junzhiit.nengji.model.SystemUser;
import com.junzhiit.nengji.model.SystemUserRole;
import com.junzhiit.nengji.model.WechatConfig;
import com.junzhiit.nengji.model.enums.AuditStatus;
import com.junzhiit.nengji.model.enums.DefaultType;
import com.junzhiit.nengji.model.enums.GoodsStatus;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.RegistStatus;
import com.junzhiit.nengji.model.enums.ShopIsRecentChange;
import com.junzhiit.nengji.model.enums.ShopStatus;
import com.junzhiit.nengji.model.enums.SystemUserStatus;
import com.intranet.transport.object.ShopAreaTO;

@Service
public class ShopServiceImpl extends BaseServiceImpl implements ShopService {

	@Autowired
	private ShopDAO shopDAO;

	@Autowired
	private ShopInfoDAO shopInfoDAO;

	@Autowired
	private SystemUserCacheDAO systemUserCacheDAO;

	@Autowired
	private WechatConfigDAO wechatConfigDAO;

	@Autowired
	private SystemUserDAO systemUserDAO;

	@Autowired
	private ShopsLocatedDAO shopsLocatedDAO;

	@Autowired
	private GoodsDAO goodsDAO;

	@Autowired
	private RoleDAO roleDAO;

	@Autowired
	private SystemUserRoleDAO systemUserRoleDAO;

	@Autowired
	private BankCardCheckCountDAO bankCardCheckCountDAO;

	@Autowired
	private ChainDAO chainDAO;
	
	@Autowired
	private RabbitMQService rabbitMQService;

	@Value("${upload.temp}")
	private String uploadPath;

	@Value("${upload.mall.shop}")
	private String shopPath;

	@Value("${upload.mall.shop.qrcode}")
	private String shopQrcodePath;
	
	//阿里云API的bucket名称
	@Value("${oss.backet.name}")
	private String backetName;

	@Override
	public Map<String, Object> findAll(DataTablesParamVO dtp, ShopVO shopVO) {
		Shop shop = new Shop();
		BeanUtils.copyProperties(shopVO, shop);

		List<ShopBO> list = shopDAO.findAll(shop, dtp.getStart(), dtp.getLength());
		int totalCount = shopDAO.getTotalCount(shop);
		return ViewObjectUtil.dataTables(list, dtp.getDraw(), totalCount);
	}

	@Override
	public ResultVO findById(String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		if (shop.getWithdrawalMoney() == null) {
			shop.setWithdrawalMoney(0.00);
		}

		result.setData(shop);

		return result;
	}

	@Override
	public ResultVO getShopById(String id) {
		ResultVO result = new ResultVO();
		Shop shop = shopDAO.query(id);
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		shop.setIsRecentChange(ShopIsRecentChange.NO.toIntStatus());
		shopDAO.update(shop);
		ShopBO shopBO = shopDAO.getShopById(id);
		if (shopBO.getExpireTime() != null) {
			shopBO.setShopExpireTime(DateUtil.format(shopBO.getExpireTime()));
		}
		result.setData(shopBO);
		return result;
	}

	@Override
	@Transactional
	public ResultVO update(ShopUpdateVO shopUpdateVO) {
		ResultVO result = new ResultVO();
		Shop shops = shopDAO.query(shopUpdateVO.getShopId());
		if (shops == null) {
			throw new ShopNotFoundException("门店找不到");
		}
		BeanUtils.copyProperties(shopUpdateVO, shops);
		if (shopUpdateVO.getExpireTime() != null) {
			shops.setExpireTime(DateUtil.getDateEnd(shopUpdateVO.getExpireTime()));
			shops.setIsRemind(Is.NO.toIntValue());
			shops.setIsRemindExpire(Is.NO.toIntValue());
		}
		shops.setIsSetType(Is.YES.toIntValue());
		shopDAO.update(shops);
		rabbitMQService.shopUpdate(shops);
		return result;
	}

	@Override
	public ResultVO getShopList() {
		ResultVO result = new ResultVO();
		result.setData(shopDAO.getShopList());
		return result;
	}

	@Override
	public ResultVO getById(String sessionId) {
		ResultVO result = new ResultVO();

		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		ShopInfoBO shopInfoBO = shopDAO.findById(systemUserSessionVO.getSystemId());
		if (shopInfoBO == null) {
			throw new ShopNotFoundException("店铺不存在");
		}

		ShopVO shopVO = new ShopVO();
		BeanUtils.copyProperties(shopInfoBO, shopVO);

		String bannerImages = shopInfoBO.getBannerImages();
		if (StringUtils.isNotBlank(bannerImages)) {
			List<String> images = Arrays.asList(bannerImages.split("\\,"));
			shopVO.setBannerImages(images);
		}

		String openingHours = shopInfoBO.getOpeningHours();

		if (StringUtils.isNotBlank(openingHours)) {
			String[] hours = openingHours.split("-");
			if (hours.length >= 2) {
				shopVO.setStartTime(hours[0]);
				shopVO.setEndTime(hours[1]);
			}
		}

		result.setData(shopVO);
		return result;
	}

	@Override
	public ResultVO editShop(ShopEditVO shopEditVO) {
		ResultVO result = new ResultVO();

		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(shopEditVO.getSessionId()), SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		
		Shop updateShop = new Shop();
		BeanUtils.copyProperties(shopEditVO, updateShop);
		if (shop.getAuditStatus() == AuditStatus.AUDITFAIL.toIntStatus()) {
			updateShop.setAuditStatus(AuditStatus.AUDIT.toIntStatus());
		} else {
			updateShop.setIsRecentChange(ShopIsRecentChange.YES.toIntStatus());
		}
		List<String> bannerImages = shopEditVO.getBannerImages();
		if (StringUtils.isNoneBlank(shop.getBannerImages())) {
			List<String> oldBannderImages = Arrays.asList(StringUtils.split(shop.getBannerImages(), ","));
			bannerImages.addAll(oldBannderImages);
		}
		updateShop.setBannerImages(StringUtils.join(bannerImages, ","));
		updateShop.setId(shop.getId());
		boolean data = shopDAO.update(updateShop);

		if (StringUtils.isNotBlank(shopEditVO.getShopHeadImgUrl())) {
			//FileUtil.moveFile(uploadPath + shopEditVO.getShopHeadImgUrl(), shopPath);
			boolean is = AliyunOSSClientUtil.moveFile(backetName,shopEditVO.getShopHeadImgUrl(), shopPath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+shopEditVO.getShopHeadImgUrl());
			}
		}
		if (StringUtils.isNotBlank(shopEditVO.getBackgroundImage())) {
			//FileUtil.moveFile(uploadPath + shopEditVO.getBackgroundImage(), shopPath);
			boolean is = AliyunOSSClientUtil.moveFile(backetName,shopEditVO.getBackgroundImage(), shopPath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+shopEditVO.getBackgroundImage());
			}
		}
		for (String bannerImage : bannerImages) {
			//FileUtil.moveFile(uploadPath + bannerImage, shopPath);
			boolean is = AliyunOSSClientUtil.moveFile(backetName,bannerImage, shopPath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+bannerImage);
			}
		}
		
		rabbitMQService.shopUpdate(updateShop);
		result.setData(data);
		return result;
	}

	@Override
	public ResultVO delShopHeadImgUrl(String shopHeadImgUrl, String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		shop.setShopHeadImgUrl(null);
		shopDAO.update(shop, true);

		//FileUtil.removeFile(shopPath + shopHeadImgUrl);
		AliyunOSSClientUtil.removeFile(backetName, shopPath+shopHeadImgUrl);
		return result;
	}

	@Override
	public ResultVO delBackgroundImage(String backgroundImage, String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		shop.setBackgroundImage(null);
		shopDAO.update(shop, true);

		AliyunOSSClientUtil.removeFile(backetName, shopPath + backgroundImage);
		return result;
	}

	@Override
	public ResultVO delBannerImages(String bannerImage, String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}

		String[] arr = StringUtils.split(shop.getBannerImages(), ",");
		List<String> oldBannderImages = new ArrayList<String>(Arrays.asList(arr));
		int index = oldBannderImages.indexOf(bannerImage);
		if (index != -1) {
			oldBannderImages.remove(index);
			shop.setBannerImages(StringUtils.join(oldBannderImages, ","));
		}

		shopDAO.update(shop, true);

		AliyunOSSClientUtil.removeFile(backetName, shopPath + bannerImage);
		return result;
	}

	@Override
	public ResultVO merchantsAudit(ShopVO shopVO) {
		ResultVO result = new ResultVO();
		ShopBO sb=new ShopBO();
		BeanUtils.copyProperties(shopVO, sb);
		Shop shop = shopDAO.query(shopVO.getId());
		ShopsLocated shopsLocated = shopsLocatedDAO.findByShopId(shopVO.getId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		shop.setAuditStatus(shopVO.getAuditStatus());
		String smsModel=null;
		SendPhoneMessageBO spmb=new SendPhoneMessageBO();
		
		if (shop.getAuditStatus() == AuditStatus.AUDITFAIL.toIntStatus()) {
			shop.setAuditFailDescription(shopVO.getAuditFailDescription());
			shop.setStatus(ShopStatus.STOP.toIntStatus());
			smsModel = SmsUtil.SHOP_MERCHANTS_AUDIT_FAIL;
			spmb.setAuditFailDescription(sb.getAuditFailDescription());
			if (shopsLocated != null) {
				shopsLocated.setRegistStatus(RegistStatus.AUDITFAIL.toIntStatus());
				shopsLocatedDAO.update(shopsLocated);
			}
			
		}else if (shop.getAuditStatus() == AuditStatus.AUDITSUCCESS.toIntStatus()) {
			shop.setIsExpire(Is.NO.toIntValue());
			shop.setIsRemind(Is.NO.toIntValue());
			shop.setIsRemindExpire(Is.NO.toIntValue());
			if (shopsLocated != null) {
				shopsLocated.setRegistStatus(RegistStatus.AUDITSUCCESS.toIntStatus());
				shopsLocatedDAO.update(shopsLocated);
			}
			smsModel=SmsUtil.SHOP_MERCHANTS_AUDIT_SUCCESS;
			
			rabbitMQService.shopUpdate(shop);
		}
		shopDAO.update(shop);
		String mobilePhone = shop.getMobilePhone();
		spmb.setMobilePhone(mobilePhone);
		spmb.setSmsModel(smsModel);
		SmsUtil.sendPhoneMessage(spmb);
		return result;
	}

	@Override
	public ResultVO getShopWechatConfig(String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		WechatConfigBO wechatConfigBO = wechatConfigDAO.getWechatConfigByShopId(systemUserSessionVO.getSystemId());
		WechatConfigVO wechatConfigVO = new WechatConfigVO();
		BeanUtils.copyProperties(wechatConfigBO, wechatConfigVO);
		result.setData(wechatConfigVO);
		return result;
	}

	@Override
	public ResultVO addOrUpdateWechatConfig(WechatConfig wechatConfig, String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		try {
			if (StringUtils.isBlank(wechatConfig.getId())) {
				wechatConfig.setCsId(systemUserSessionVO.getSystemId());
				wechatConfigDAO.insert(wechatConfig);
			} else {
				WechatConfig params = wechatConfigDAO.query(wechatConfig.getId());
				BeanUtils.copyProperties(wechatConfig, params);
				wechatConfigDAO.update(params);
			}
		} catch (Exception e) {
			result.setStatus(CMSCodeStatus.FAILED);
			result.setMessage(e.getMessage());
		}
		return result;
	}

	@Override
	public void updateShopExpireTime() {
		List<Shop> shops = shopDAO.getAllShop();
		Date now = new Date();
		for (Shop shop : shops) {
			if (shop.getExpireTime() != null && shop.getExpireTime().getTime() <= now.getTime()) {
				shop.setAuditStatus(AuditStatus.AUDITFAIL.toIntStatus());
				shop.setStatus(ShopStatus.STOP.toIntStatus());
				shop.setIsExpire(Is.YES.toIntValue());
				List<Goods> goods = goodsDAO.findAllGoods(shop.getId());
				for (Goods good : goods) {
					good.setStatus(GoodsStatus.INACTIVE.toIntStatus());
					good.setAuditFailDescription("店铺已到期");
					goodsDAO.update(good);
				}
				shopDAO.update(shop);
			}
		}
	}

	@Override
	public ResultVO createQrcode(String shopId) {
		ResultVO result = new ResultVO();
		Shop shop = shopDAO.query(shopId);
		String wechatCodeUrl=shopId + ".png";
		if(shop.getIsPlatform() == Is.YES.toIntValue()){
			WechatConfig wechatConfig = wechatConfigDAO.getWechatConfigByCsId(shopId);
			if(wechatConfig == null){
				throw new WechatConfigNotFoundException("微信配置未配置");
			}
			
			WeChatUtils.wxQRCode(wechatConfig,backetName,shop.getCode(), shop.getId(), shopQrcodePath, wechatCodeUrl,Constants.SHOP_URL);
			shop.setWechatCodeUrl(wechatCodeUrl);
			shopDAO.update(shop);
			
		}else{
			WeChatUtils.wxQRCode(backetName,shop.getCode(), shop.getId(), shopQrcodePath, wechatCodeUrl,Constants.SHOP_URL);
			shop.setWechatCodeUrl(wechatCodeUrl);
			shopDAO.update(shop);
		}
		result.setData(wechatCodeUrl);
		return result;
	}

	@Override
	public ResultVO getGoodsAuditShopSelect() {
		ResultVO result = new ResultVO();
		List<Shop> list = shopDAO.getGoodsAuditShopSelect();
		List<ShopSelectVO> selectVOList = new ArrayList<ShopSelectVO>();
		for (Shop shop : list) {
			ShopSelectVO selectVO = new ShopSelectVO();
			BeanUtils.copyProperties(shop, selectVO);
			selectVOList.add(selectVO);
		}
		result.setData(selectVOList);
		return result;
	}

	public void sendRemindInfo() {
		Date now = new Date();
		String date = null;
		List<Shop> shops = shopDAO.getSoonExpireShop();
		for (Shop shop : shops) {
			if(shop.getMobilePhone()==null||shop.getMobilePhone()==""){
				throw new SendSMSFaileException("该店铺无手机号码,无法发送手机验证码");
			}
			if (shop.getExpireTime() != null && DateUtil.getDate(shop.getExpireTime(), -15).getTime() < now.getTime()) {
				date = DateUtil.format(shop.getExpireTime());
				SMSParams sms = new SMSParams();
				sms.setSignName(SmsUtil.ALIYUN_SMS_SIGN_NAME);
				sms.setTemplateCode(SmsUtil.ALIYUN_SMS_CONTRACT_EXPIRE);
				sms.setPhoneNumbers(new String[] { shop.getMobilePhone() });
				sms.setParamKeys(new String[] { SmsUtil.KEY_DATE, SmsUtil.KEY_SEND_MOBLIE_PHONE });
				sms.setParamValues(new String[] { date, SmsUtil.REMIND_CLOSE_SERVICE });
				try {
					SendSmsResponse response = SmsUtil.sendSms(sms);
					if (response.getCode() != null && response.getCode().equals("OK")) {
						shop.setIsRemind(Is.YES.toIntValue());
						shopDAO.update(shop);
					} else if (response.getCode() != null && response.getCode().equals(SmsUtil.LIMIT_CONTROL_ERROR)) {
						throw new LimitControlException("不能过于频繁发送验证码,请稍后再发");
					} else {
						throw new SendSMSFaileException("无法发送手机验证码");
					}
				} catch (ClientException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public ResultVO getShopList(String sessionId, Integer type) {
		ResultVO result = new ResultVO();
		List<Shop> list = new ArrayList<Shop>();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		if (StringUtils.isNotBlank(systemUserSessionVO.getSystemId())) {
			Chain chain = chainDAO.query(systemUserSessionVO.getSystemId());
			list = shopDAO.getShopList(type, chain.getId());
		} else {
			list = shopDAO.getShopList(type, null);
		}

		List<ShopSelectVO> selectVOList = new ArrayList<ShopSelectVO>();
		for (Shop shop : list) {
			ShopSelectVO selectVO = new ShopSelectVO();
			BeanUtils.copyProperties(shop, selectVO);
			selectVOList.add(selectVO);
		}
		result.setData(selectVOList);
		return result;
	}

	@Transactional
	@Override
	public ResultVO add(SystemUserAddVO systemUserAddVO, ShopAddVO shopAddVO, String setMealId, String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);

		Chain chainParam = new Chain();
		chainParam.setSystemUserId(systemUserSessionVO.getSystemUserId());
		Chain chain = chainDAO.getChain(chainParam);

		// 用户基本信息
		String mobilePhone = systemUserAddVO.getMobilePhone();
		String code = systemUserAddVO.getCode();
		String email = systemUserAddVO.getEmail();
		String password = systemUserAddVO.getPassword();
		String confirmPassword = systemUserAddVO.getConfirmPassword();
		if (!password.equals(confirmPassword)) {
			throw new InconsistentPasswordException("密码与确认密码不一致");
		}

		String MD5password = EncryptMD5Util.getMD5(password);
		PhoneCodeVO phoneCode = systemUserCacheDAO.getHash(DIYKey.getMobilePhoneCodeKey(mobilePhone),
				PhoneCodeVO.class);
		// 验证码不一致
		if (!phoneCode.getCode().equals(code)) {
			throw new MobilePhoneCodeErrorException("验证码不一致");
		}
		if (phoneCode.getTimestamp() < new Date().getTime()) {
			throw new MobilePhoneCodeTimeoutException("验证码已过期");
		}
		int count = systemUserDAO.getMobilePhoneCount(mobilePhone);
		// 已存在手机号码
		if (count > 0) {
			throw new MobilePhoneHasUsedException("手机号码已存在");
		}
		// 已存在邮箱
		int countEmail = systemUserDAO.checkEmail(email);
		if (countEmail > 0) {
			throw new EmailIsExistException("邮箱已存在");
		}

		SystemUser systemUser = new SystemUser();
		BeanUtils.copyProperties(systemUserAddVO, systemUser);
		systemUser.setPassword(MD5password);
		systemUser.setIsChain(Is.NO.toIntValue());
		systemUser.setSafetyLevel(0);
		systemUser.setIsMainAccount(Is.YES.toIntValue());
		systemUser.setStatus(SystemUserStatus.ACTIVE.toIntStatus());
		systemUser.setIsAuth(Is.NO.toIntValue());
		systemUser.setIsUpdatePassword(Is.NO.toIntValue());
		systemUser.setRegiestStatus(RegistStatus.INDUSTRY.toIntStatus());
		systemUser.setIsImproveShop(Is.YES.toIntValue());
		systemUser.setIsImproveMeal(Is.YES.toIntValue());
		systemUser.setIsImproveBusiness(Is.YES.toIntValue());
		SystemUser newSystemUser = systemUserDAO.insert(systemUser);

		// 店铺基本信息
		Shop shop = new Shop();
		BeanUtils.copyProperties(shopAddVO, shop);
		shop.setMainAccountId(newSystemUser.getId());
		shop.setStatus(ShopStatus.STOP.toIntStatus());
		shop.setIsReceiveOrder(Is.YES.toIntValue());
		shop.setSetMealId(setMealId);
		shop.setIsChain(Is.YES.toIntValue());
		shop.setIsSetType(Is.YES.toIntValue());
		//店铺跟随品牌的属性
		shop.setChainId(chain.getId());
		shop.setProfit(chain.getProfit());
		shop.setIsOpenSell(chain.getIsOpenSell());
		shop.setIsOpenRebate(chain.getIsOpenRebate());
		shop.setExpireTime(chain.getExpireTime());
		shop.setAuditStatus(AuditStatus.AUDITSUCCESS.toIntStatus());
		Shop data = shopDAO.insert(shop);

		if (data == null) {
			throw new RegisteredFailureException("创建失败！");
		}

		newSystemUser.setSystemId(data.getId());
		systemUserDAO.update(newSystemUser);

		ShopInfo shopInfo = new ShopInfo();
		shopInfo.setShopId(data.getId());
		shopInfoDAO.insert(shopInfo);

		// 添加商户默认角色
		SystemUserRole systemUserRole = new SystemUserRole();
		systemUserRole.setSystemUserId(systemUser.getId());

		int defaultCount = roleDAO.getIsDefaultCount(DefaultType.CHAIN_SHOP.toIntStatus());
		if (defaultCount <= 0) {
			throw new RoleNotFoundException("默认角色不存在");
		}

		Role role = roleDAO.getDefaultRole(DefaultType.CHAIN_SHOP.toIntStatus());
		
		systemUserRole.setRoleId(role.getId());
		systemUserRoleDAO.insert(systemUserRole);

		// 创建该店铺验证银行卡次数
		String key = DIYKey.getBankCardCheckCount(data.getId());
		bankCardCheckCountDAO.addString(key, Constants.CHECK_COUNT);

		result.setData(data);

		return result;
	}

	@Override
	public Map<String, Object> findShopList(DataTablesParamVO dtp, ShopVO shopVO) {
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(shopVO.getSessionId()), SystemUserSessionVO.class);

		Shop shop = new Shop();
		BeanUtils.copyProperties(shopVO, shop);

		List<ShopBO> list = shopDAO.findListByChain(systemUserSessionVO.getSystemUserId(), shop, dtp.getStart(),
				dtp.getLength());
		int totalCount = shopDAO.getTotalCountByChain(systemUserSessionVO.getSystemUserId(), shop);
		return ViewObjectUtil.dataTables(list, dtp.getDraw(), totalCount);
	}

	@Override
	public void sendRemindExpireInfo() {
		List<Shop> shops = shopDAO.getExpireShop();
		for (Shop shop : shops) {
			if(shop.getMobilePhone()==null||shop.getMobilePhone()==""){
				throw new SendSMSFaileException("该店铺无手机号码,无法发送手机验证码");
			}
			if (shop.getExpireTime() != null) {
				SMSParams sms = new SMSParams();
				sms.setSignName(SmsUtil.ALIYUN_SMS_SIGN_NAME);
				sms.setTemplateCode(SmsUtil.ALIYUN_SMS_SHOP_CLOSE);
				sms.setPhoneNumbers(new String[] { shop.getMobilePhone() });
				sms.setParamKeys(new String[] { SmsUtil.KEY_SEND_MOBLIE_PHONE });
				sms.setParamValues(new String[] { SmsUtil.SHOP_CLOSE_SERVICE });
				try {
					SendSmsResponse response = SmsUtil.sendSms(sms);
					if (response.getCode() != null && response.getCode().equals("OK")) {
						shop.setIsRemindExpire(Is.YES.toIntValue());
						shopDAO.update(shop);
					} else if (response.getCode() != null && response.getCode().equals(SmsUtil.LIMIT_CONTROL_ERROR)) {
						throw new LimitControlException("不能过于频繁发送验证码,请稍后再发");
					} else {
						throw new SendSMSFaileException("无法发送手机验证码");
					}
				} catch (ClientException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public ResultVO getShopMainAccount(String sessionId) {
		ResultVO result = new ResultVO();

		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);

		String mobilePhone = shopDAO.getMainAccountPhone(systemUserSessionVO.getSystemId());
		result.setData(mobilePhone);
		return result;
	}

	@Override
	public ResultVO findAllConcise() {
		ResultVO result = new ResultVO();
		result.setData(shopDAO.findConstrictAll());
		return result;
	}

	@Override
	public Map<String, Object> findGoodsListByShopId(DataTablesParamVO dtp,GoodsListVO glv) {
		GoodsListBO glb=new GoodsListBO();
		BeanUtils.copyProperties(glv, glb);
		List<GoodsBO> list=shopDAO.findGoodsListByShopId(glb, dtp.getStart(), dtp.getLength());
		int totalCount=shopDAO.getTotalCountByShopId(glb);
		
		return ViewObjectUtil.dataTables(list,dtp.getDraw(), totalCount);
	}

	@Override
	public List<ShopAreaTO> findTop200ByTime(String time) {
		List<Shop> list = shopDAO.findTop200ByTime(time);
		
		List<ShopAreaTO> listTO = new ArrayList<ShopAreaTO>();
		for (Shop shop : list) {
			ShopAreaTO shopTO = new ShopAreaTO();
			BeanUtils.copyProperties(shop, shopTO);
			listTO.add(shopTO);
		}
		
		return listTO;
	}
	
	@Override
	public ResultVO getProgramShop(){
		ResultVO result=new ResultVO();
		List<Shop> data=shopDAO.getProgramShop();
		result.setData(data);
		return result;
	}
	
	@Override
	public ResultVO getShopList(String sessionId) {
		ResultVO result=new ResultVO();
		SystemUserSessionVO session=systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		String chainId=session.getSystemId();
		Chain chain=chainDAO.query(chainId);
		if(chain==null){
			throw new ChainNotFoundException("品牌不存在");
		}
		List<Shop> shopList=shopDAO.getShopList(chainId);
		result.setData(shopList);
		return result;
	}

	@Override
	public ResultVO checkShopType(String sessionId) {
		ResultVO result=new ResultVO();
		SystemUserSessionVO session=systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId), SystemUserSessionVO.class);
		if(shopDAO.query(session.getSystemId())!=null){
			result.setData(Is.NO.toIntValue());
		}else if(chainDAO.query(session.getSystemId())!=null){
			result.setData(Is.YES.toIntValue());
		}
		return result;
	}

	@Override
	public ResultVO updateByShopId(ShopEditVO shopEditVO) {
		ResultVO result=new ResultVO();
		Shop shop = shopDAO.query(shopEditVO.getId());
		shop.setName(shopEditVO.getName());
		shop.setMobilePhone(shopEditVO.getMobilePhone());
		shop.setIndustryId(shopEditVO.getIndustryId());
		shop.setAreaProvinceId(shopEditVO.getAreaProvinceId());
		shop.setAreaCountyId(shopEditVO.getAreaCountyId());
		shop.setAreaCityId(shopEditVO.getAreaCityId());
		shop.setIsMail(shopEditVO.getIsMail());
		shop.setIsShop(shopEditVO.getIsShop());
		shop.setIsDelivery(shopEditVO.getIsDelivery());
		shop.setIsEat(shopEditVO.getIsEat());
		shop.setIsReceiveOrder(shopEditVO.getIsReserve());
		shop.setIsCustomGoods(shopEditVO.getIsCustomGoods());
		shopDAO.update(shop);
		return result;
	}
	
	@Override
	public Map<String, Object> getList(DataTablesParamVO dtp, ShopVO sv) {
		ShopBO sb=new ShopBO();
		BeanUtils.copyProperties(sv, sb);
		List<Shop> sList=shopDAO.getList(sb, dtp.getStart(), dtp.getLength());
		Integer sListCount=shopDAO.getListCount(sb);
		return ViewObjectUtil.dataTables(sList, dtp.getDraw(), sListCount);
	}
}
